const mysql = require('mysql2/promise');

async function checkLogs() {
  console.log('正在检查数据库中的日志记录...\n');

  try {
    const connection = await mysql.createConnection({
      host: '8.149.243.80',
      port: 3307,
      user: 'root',
      password: '123456',
      database: 'mqtt_app'
    });

    console.log('✅ 数据库连接成功！\n');

    // 查询总记录数
    const [countResult] = await connection.execute('SELECT COUNT(*) as total FROM logs');
    console.log(`📊 总日志记录数: ${countResult[0].total}\n`);

    // 按类型统计
    const [typeStats] = await connection.execute(`
      SELECT type, COUNT(*) as count
      FROM logs
      GROUP BY type
    `);
    console.log('📈 按类型统计:');
    typeStats.forEach(row => {
      console.log(`   - ${row.type}: ${row.count} 条`);
    });
    console.log('');

    // 查询最近10条记录
    const [recentLogs] = await connection.execute(`
      SELECT id, timestamp, type, topic,
             LEFT(message, 50) as message_preview,
             source, client_id, created_at
      FROM logs
      ORDER BY created_at DESC
      LIMIT 10
    `);

    if (recentLogs.length > 0) {
      console.log('📝 最近10条日志记录:');
      recentLogs.forEach((log, index) => {
        console.log(`\n${index + 1}. [${log.type}] ${log.timestamp}`);
        console.log(`   主题: ${log.topic || 'N/A'}`);
        console.log(`   消息: ${log.message_preview || 'N/A'}`);
        console.log(`   来源: ${log.source || 'N/A'}`);
        console.log(`   客户端ID: ${log.client_id || 'N/A'}`);
        console.log(`   创建时间: ${log.created_at}`);
      });
    } else {
      console.log('⚠️  数据库中没有任何日志记录！');
    }

    // 查询发布消息记录
    console.log('\n\n📤 发布消息记录:');
    const [publishLogs] = await connection.execute(`
      SELECT timestamp, topic, message, source, created_at
      FROM logs
      WHERE type = 'publish'
      ORDER BY created_at DESC
      LIMIT 5
    `);

    if (publishLogs.length > 0) {
      publishLogs.forEach((log, index) => {
        console.log(`\n${index + 1}. ${log.timestamp}`);
        console.log(`   主题: ${log.topic}`);
        console.log(`   消息: ${log.message}`);
        console.log(`   来源: ${log.source || 'N/A'}`);
      });
    } else {
      console.log('   ⚠️  没有发布消息记录');
    }

    // 查询接收消息记录
    console.log('\n\n📥 接收消息记录:');
    const [messageLogs] = await connection.execute(`
      SELECT timestamp, topic, message, source, created_at
      FROM logs
      WHERE type = 'message'
      ORDER BY created_at DESC
      LIMIT 5
    `);

    if (messageLogs.length > 0) {
      messageLogs.forEach((log, index) => {
        console.log(`\n${index + 1}. ${log.timestamp}`);
        console.log(`   主题: ${log.topic}`);
        console.log(`   消息: ${log.message}`);
        console.log(`   来源: ${log.source || 'N/A'}`);
      });
    } else {
      console.log('   ⚠️  没有接收消息记录');
    }

    await connection.end();
    console.log('\n\n✅ 检查完成！');

  } catch (error) {
    console.error('❌ 检查失败:', error.message);
  }
}

checkLogs();
